<?php
/**
 * @description : request a unauthorized Request Token
 * @author : stephen
 * @date : 2010/07/07
 */
require_once "TVB/OAuth/common.inc.php";
#try to get the request url
try {

    $req = OAuthRequest::from_request();
    if (isset($tvb_server) && is_object($tvb_server)) {
        //using oauth_verify to check authorized request token.
        $request = $req->get_parameters();

        //if this consumer needn't to check verifier
        if (!OAuthUtils::checkVerifiable($request['oauth_consumer_key'])) {
            $token = $tvb_server->fetch_access_token($req);
            $up_result = OAuthUtils::updateAuthorized($token,NULL,$request['oauth_token']);
            if ($up_result) {
                print $token;
                exit;
            }
            throw new OAuthException('Can not Update Access Token'.$token);
            #echo OAuthConfig::UPDATE_ACCESS_TOKEN_FAIL;
            exit;
        }
        
        if (empty($request['oauth_verifier']) || empty($request['oauth_token'])) {
            throw new OAuthException('Unauthorized Request Token '.$request['oauth_token']);
            #echo OAuthConfig::MISSING_NECESSARY_PARAM;
            exit;
        }
        

        //check this request token is or not authorized?
        $result = OAuthUtils::checkTokenAuthorized($request['oauth_verifier']);
        if (!empty($result) && ($request['oauth_token']==$result)) {
            $token = $tvb_server->fetch_access_token($req);
            $up_result = OAuthUtils::updateAuthorized($token,$request['oauth_verifier'],$request['oauth_token']);
            if ($up_result) {
                //saving access token to mc by login id.
                OAuthUtils::saveAccessTokenToMc($token);
                print $token;
                exit;
            }
            else {
                throw new OAuthException('Can not Update Access Token '.$token);
                #echo OAuthConfig::UPDATE_ACCESS_TOKEN_FAIL;
                exit;
            }
        }
        else {
            throw new OAuthException('Unauthorized Request Token '.$request['oauth_token']);
            #echo OAuthConfig::AUTHORIZED_REQUEST_TOKEN_FAIL;
            exit;
        }
    }
    else {
        throw new OAuthException('Unauthorized Request Token '.$request['oauth_token']);
        #echo OAuthConfig::MISSING_NECESSARY_PARAM;
        exit;
    }
}
catch (OAuthException $e) {
    #echo OAuthConfig::OTHER_OAUTH_ERROR;
    print($e->getMessage() . "\n<hr />\n");
    print_r($req);
    exit;
}

?>
